package com.cpone.cloudweb.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPool {
    private static final Logger log= LoggerFactory.getLogger(ThreadPool.class);
    private int threadsize;
    private ThreadPoolExecutor threadPool=null;
    public List<Future> executeResult= Collections.synchronizedList(new ArrayList<Future>());

    /**
     * 线程池线程数量
     * @param threadSize
     */
    public ThreadPool(int threadSize){
        this.threadsize=threadSize;
        threadPool=(ThreadPoolExecutor) Executors.newFixedThreadPool(this.threadsize);
    }
    public ThreadPool(int threadsize,final String threadName){
        this.threadsize=threadsize;
        threadPool=(ThreadPoolExecutor) Executors.newFixedThreadPool(this.threadsize, new ThreadFactory() {
            AtomicInteger atomicInteger=new AtomicInteger();
            @Override
            public Thread newThread(Runnable r) {
                Thread thread=(Thread) r;
                thread.setName(threadName+"----"+atomicInteger);
                return thread;
            }
        });
    }
    public void put(Runnable task) throws Exception{
        try{
            if(threadPool.getActiveCount()<threadsize){
                executeResult.add(threadPool.submit(task));
            }else{
                while (true){
                    Thread.sleep(1000);
                    if(threadPool.getActiveCount()<threadsize){
                        executeResult.add(threadPool.submit(task));
                        break;
                    }
                }
            }
        }
        catch (Exception e){
            log.error("线程池添加任务异常，原因如下：\n"+e);
        }
    }
    public long getActiveCount(){
        return threadPool.getActiveCount();
    }
    public ThreadPoolExecutor getThreadPool(){
        if(threadPool==null){
            threadPool=(ThreadPoolExecutor)Executors.newFixedThreadPool(threadsize);
        }
        return this.threadPool;

    }
}
